package com.main.zlw.zlwaudiorecorder.slice;


import com.main.zlw.zlwaudiorecorder.AudioView;
import com.main.zlw.zlwaudiorecorder.ResourceTable;
import com.main.zlw.zlwaudiorecorder.TestHzAbility;
import com.main.zlw.zlwaudiorecorder.base.MyApp;
import com.zlw.main.recorderlib.RecordManager;
import com.zlw.main.recorderlib.recorder.RecordConfig;
import com.zlw.main.recorderlib.recorder.RecordHelper;
import com.zlw.main.recorderlib.recorder.listener.RecordFftDataListener;
import com.zlw.main.recorderlib.recorder.listener.RecordResultListener;
import com.zlw.main.recorderlib.recorder.listener.RecordSoundSizeListener;
import com.zlw.main.recorderlib.recorder.listener.RecordStateListener;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Environment;
import ohos.media.audio.AudioStreamInfo;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final String TAG = MainAbilitySlice.class.getSimpleName();

    Button btRecord;
    Button btStop;
    Text tvState;
    Text tvSoundSize;
    RadioContainer rgAudioFormat;
    RadioContainer rgSimpleRate;
    RadioContainer tbEncoding;
    AudioView audioView;
    RadioContainer spUpStyle;
    RadioContainer spDownStyle;
    private int RecordFormat = 0;
    private boolean isStart = false;
    private boolean isPause = false;
    final RecordManager recordManager = RecordManager.getInstance();
    private static final String[] STYLE_DATA = new String[]{"STYLE_ALL", "STYLE_NOTHING", "STYLE_WAVE", "STYLE_HOLLOW_LUMP"};


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_main);

        btRecord = (Button) findComponentById(ResourceTable.Id_btRecord);
        btStop = (Button) findComponentById(ResourceTable.Id_btStop);
        tvState = (Text) findComponentById(ResourceTable.Id_tvState);
        tvSoundSize = (Text) findComponentById(ResourceTable.Id_tvSoundSize);
        rgAudioFormat = (RadioContainer) findComponentById(ResourceTable.Id_rgAudioFormat);
        RadioButton wav = (RadioButton) findComponentById(ResourceTable.Id_rbWav);
        wav.setChecked(true);
        rgSimpleRate = (RadioContainer) findComponentById(ResourceTable.Id_rgSimpleRate);
        RadioButton rb16 = (RadioButton) findComponentById(ResourceTable.Id_rb16K);
        rb16.setChecked(true);
        tbEncoding = (RadioContainer) findComponentById(ResourceTable.Id_tbEncoding);
        RadioButton rb16Bit = (RadioButton) findComponentById(ResourceTable.Id_rb16Bit);
        rb16Bit.setChecked(true);
        audioView = (AudioView) findComponentById(ResourceTable.Id_audioView);
        spUpStyle = (RadioContainer)findComponentById(ResourceTable.Id_spUpStyle);
        RadioButton upStyle_all = (RadioButton) findComponentById(ResourceTable.Id_upStyle_all);
        upStyle_all.setChecked(true);
        spDownStyle = (RadioContainer)findComponentById(ResourceTable.Id_spDownStyle);
        RadioButton downStyle_all = (RadioButton) findComponentById(ResourceTable.Id_downStyle_all);
        downStyle_all.setChecked(true);

        findComponentById(ResourceTable.Id_jumpTestActivity).setClickedListener(this);
        btRecord.setClickedListener(this);
        btStop.setClickedListener(this);
        tvState.setClickedListener(this);

        initAudioView();
        initEvent();
        initRecord();
    }

    @Override
    public void onActive() {
        super.onActive();
//        doStop();
        initRecordEvent();
    }

    @Override
    protected void onStop() {
        super.onStop();
        doStop();
    }

    private void initAudioView() {
    }

    private void setRecordFormat(){
        switch (RecordFormat) {
            case 0:
                recordManager.changeFormat(RecordConfig.RecordFormat.PCM);
                break;
            case 1:
                recordManager.changeFormat(RecordConfig.RecordFormat.MP3);
                break;
            case 2:
                recordManager.changeFormat(RecordConfig.RecordFormat.WAV);
                break;
            default:
        }
    }

    private void initEvent() {
        rgAudioFormat.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {
                switch (i) {
                    case 0:
                        RecordFormat = 0;
                        recordManager.changeFormat(RecordConfig.RecordFormat.PCM);
                        break;
                    case 1:
                        RecordFormat = 1;
                        recordManager.changeFormat(RecordConfig.RecordFormat.MP3);
                        break;
                    case 2:
                        RecordFormat = 2;
                        recordManager.changeFormat(RecordConfig.RecordFormat.WAV);
                        break;
                    default:
                        break;
                }
            }

        });

        rgSimpleRate.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {

                switch (i) {
                    case 0:
                        recordManager.changeRecordConfig(recordManager.getRecordConfig().setSampleRate(8000));
                        break;
                    case 1:
                        recordManager.changeRecordConfig(recordManager.getRecordConfig().setSampleRate(16000));
                        break;
                    case 2:
                        recordManager.changeRecordConfig(recordManager.getRecordConfig().setSampleRate(44100));
                        break;
                    default:
                        break;
                }
            }
        });

        tbEncoding.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {
                switch (i) {
                    case 0:
                        recordManager.changeRecordConfig(recordManager.getRecordConfig().setEncodingConfig(AudioStreamInfo.EncodingFormat.ENCODING_PCM_8BIT));
                        break;
                    case 1:
                        recordManager.changeRecordConfig(recordManager.getRecordConfig().setEncodingConfig(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT));
                        break;
                    default:
                        break;
                }
            }
        });
        spUpStyle.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {
                audioView.setStyle(AudioView.ShowStyle.getStyle(STYLE_DATA[i]), audioView.getDownStyle());
            }
        });
        spDownStyle.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {
                audioView.setStyle(audioView.getUpStyle(), AudioView.ShowStyle.getStyle(STYLE_DATA[i]));
            }
        });

    }

    private void initRecord() {
        recordManager.init(MyApp.getInstance(), true);
        recordManager.changeFormat(RecordConfig.RecordFormat.WAV);
//        String recordDir = String.format(Locale.getDefault(), "%s",
//                getExternalFilesDir(Environment.DIRECTORY_MUSIC));
//        recordManager.changeRecordDir(recordDir);
        initRecordEvent();
    }

    private void initRecordEvent() {
        recordManager.setRecordStateListener(new RecordStateListener() {
            @Override
            public void onStateChange(RecordHelper.RecordState state) {

                switch (state) {
                    case PAUSE:
                        tvState.setText("暂停中");
                        break;
                    case IDLE:
                        tvState.setText("空闲中");
                        break;
                    case RECORDING:
                        tvState.setText("录音中");
                        break;
                    case STOP:
                        tvState.setText("停止");
                        break;
                    case FINISH:
                        tvState.setText("录音结束");
                        tvSoundSize.setText("---");
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onError(String error) {
            }
        });
        recordManager.setRecordSoundSizeListener(new RecordSoundSizeListener() {
            @Override
            public void onSoundSize(int soundSize) {
                tvSoundSize.setText(String.format(Locale.getDefault(), "声音大小：%s db", soundSize));
            }
        });
        recordManager.setRecordResultListener(new RecordResultListener() {
            @Override
            public void onResult(File result) {
                try {
                    showToast("录音文件： " + result.getCanonicalPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        recordManager.setRecordFftDataListener(new RecordFftDataListener() {
            @Override
            public void onFftData(byte[] data) {
                audioView.setWaveData(data);
            }
        });
    }

    private void doStop() {
        recordManager.stop();
        btRecord.setText("开始");
        isPause = false;
        isStart = false;
    }

    private void doPlay() {
        if (isStart) {
            recordManager.pause();
            btRecord.setText("开始");
            isPause = true;
            isStart = false;
        } else {
            if (isPause) {
                recordManager.resume();
            } else {
                recordManager.start();
            }
            btRecord.setText("暂停");
            isStart = true;
        }
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_btRecord:
                setRecordFormat();
                doPlay();
                break;
            case ResourceTable.Id_btStop:
                doStop();
                break;
            case ResourceTable.Id_jumpTestActivity:
                if(isStart){
                    doStop();
                }
                Intent secondIntent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName(TestHzAbility.class.getName())
                        .build();
                secondIntent.setOperation(operation);
                startAbility(secondIntent);
                break;
            default:
        }
    }
    
    private void showToast(String toastStr){
        ToastDialog toastDialog = new ToastDialog(getContext());
        toastDialog.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        toastDialog.setText(toastStr);
        Text toastText=(Text) toastDialog.getComponent();
        if(toastText!=null)
        {
            toastText.setMultipleLine(true);
            toastText.setTextSize(14, Text.TextSizeType.FP);
            toastText.setPaddingBottom(20);
            toastText.setPaddingTop(20);
        }
        toastDialog.show();
    }
}
